package com.bdqn.BookManage.servlet;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.bdqn.BookManage.biz.OrderBiz;
import com.bdqn.BookManage.biz.OrderGoodsBiz;
import com.bdqn.BookManage.biz.OrderSettlementsBiz;
import com.bdqn.BookManage.biz.impl.OrderBizImpl;
import com.bdqn.BookManage.biz.impl.OrderGoodsBizImpl;
import com.bdqn.BookManage.biz.impl.OrderSettlementsBizImpl;
import com.bdqn.BookManage.po.Order;
import com.bdqn.BookManage.po.OrderGoods;
import com.bdqn.BookManage.po.OrderSettlements;
import com.bdqn.BookManage.util.AlipayConfig;
import com.bdqn.BookManage.view.BookInfoView;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * @author : CP
 * @version: 1.0
 * @program : BookManage
 * @description : 生成购物订单等信息处理器
 * @date : 2020-07-31 14:03
 **/
@WebServlet("/addOrder")
public class AddOrderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        /** 实现业务层 */
        OrderBiz orderBiz = new OrderBizImpl();
        OrderGoodsBiz orderGoodsBiz = new OrderGoodsBizImpl();
        OrderSettlementsBiz orderSettlementsBiz = new OrderSettlementsBizImpl();


        /** 判断最终结果 */
        boolean result = false;
        /** 获取地址 */
        String site = req.getParameter("site");

        /** 从购物车取出选中的商品信息封装为一条订单记录 */
        Map<String, BookInfoView> cart = (Map<String, BookInfoView>) session.getAttribute("cart");

        /** 生成订单信息 */
        Order order = new Order();
        /** 订单编号 */
        order.setOrderNo(System.currentTimeMillis()+"");
        /** 订单状态 */
        order.setOrderStatus(-2);
        /** 订单总金额 */
        double sum = 0.0;
        for (BookInfoView bookInfoView: cart.values()) {
            sum += bookInfoView.getTotal();
        }
        order.setTotalMoney(sum);
        /** 是否支付 */
        order.setIsPay(0);
        /** 收货地址 */
        order.setUserAddress(site);
        /** 本次订单所得积分 */
        /** 订单备注 */
        order.setOrderRemarks("暂无备注");
        /** 下单时间 */
        order.setCreateTime(new Date());
        /** 订单是否完结 */
        order.setIsClosed(0);
        /** 订单是否有效 */
        order.setOrderFlag(1);
        /** ... 忽略的信息需支付完成后填写 */
        /** 添加信息 */
        result = orderBiz.add(order);


        /** 生成订单与商品信息关联信息 */
        for (BookInfoView bookInfoView: cart.values()) {
            OrderGoods orderGoods = new OrderGoods();
            /** 订单编号 */
            orderGoods.setOrderId(order.getOrderNo());
            /** 商品编号 */
            orderGoods.setGoodsId(bookInfoView.getBookInfo().getId());
            /** 购买数量 */
            orderGoods.setGoodsNums(bookInfoView.getAmount());
            /** 商品价格 */
            orderGoods.setGoodsPrice(bookInfoView.getBookInfo().getPrice());
            /** 商品名称 */
            orderGoods.setGoodsName(bookInfoView.getBookInfo().getBookName());
            /** 图片路径 */
            orderGoods.setGoodsThums(bookInfoView.getBookInfo().getImgUrl());
            /** 时间 */
            orderGoods.setCreateTime(new Date());
            /** 添加数据 */
            result = orderGoodsBiz.add(orderGoods);
        }


        /** 生成订单结算信息 */
        OrderSettlements orderSettlements = new OrderSettlements();
        /** 订单编号 */
        orderSettlements.setOrderId(order.getOrderNo());
        /** 结算编号 */
        orderSettlements.setSettlementNo("J"+System.currentTimeMillis());
        /** 结算类型 0:手动 1:定时 */
        orderSettlements.setSettlementType(0);
        /** 实际金额暂时不管 */
        /** 结算金额 */
        orderSettlements.setSettlementMoney(order.getTotalMoney());
        /** 创建时间 */
        orderSettlements.setCreateTime(new Date());
        /** 是否完成结算 0未结算 1已结算 */
        orderSettlements.setIsFinish(0);
        /** 结算时间暂时不管 */
        /** 备注 */
        orderSettlements.setRemarks("暂无备注");
        /** 添加数据 */
        result = orderSettlementsBiz.add(orderSettlements);

        if(result) {
            /** 移除购物车被勾选的商品信息 */
            Iterator<BookInfoView> iterator = cart.values().iterator();
            while (iterator.hasNext()) {
                /** 每次提取一条信息 */
                BookInfoView next = iterator.next();
                if (next.getIsSelected() == 1) {
                    /** 删除 */
                    iterator.remove();
                }
            }

            /** 支付宝付款 */
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                    AlipayConfig.merchant_private_key, "json", AlipayConfig.charset,
                    AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
            String out_trade_no = order.getOrderNo();
            String total_amount = String.valueOf(order.getTotalMoney());
            String subject = "购买图书";
            String body = "暂无描述";
            String timeout_express = "3m";
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\",\"total_amount\":\"" +
                    total_amount + "\",\"subject\":\"" + subject + "\",\"body\":\"" + body +
                    "\",\"timeout_express\":\"" + timeout_express + "\",\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


            try {
                String jg = (alipayClient.pageExecute(alipayRequest)).getBody();
                resp.getWriter().write(jg);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }
    }
}
